package com.xie.wechat;


import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.xie.wechat.chat.Chat;
import com.xie.wechat.chat.Msg;
import com.xie.wechat.chat.ChatAdapter;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

import androidx.fragment.app.Fragment;

public class FragmentOne extends Fragment {
    private SharedPreferences sharedPreferences = null;
    private ArrayList<Chat> mChatArrayList = new ArrayList<>();//定义一个存储信息的列表
    private EditText mInputText;//输入框
    private Button mSend;//发送按钮
    private RecyclerView mRecyclerView;//滑动框
    private ChatAdapter mAdapter;//适配器
    private boolean backFlag = false;
    private WebSocket mSocket;
    private Chat mChat;;//全局User

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment_one, container, false);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView=getActivity().findViewById(R.id.msg_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(50));//这里设置了RecyclerView子项的间隔
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new ChatAdapter(mChatArrayList);
        mRecyclerView.setAdapter(mAdapter);
        initView();
//        开启连接
        start();
        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = mInputText.getText().toString();
                if (!"".equals(content)) {
                    Msg msg = new Msg(true,content,false);
                    Integer userId ;
                    String username = "";
                    sharedPreferences = getActivity().getSharedPreferences("myinfo", MODE_PRIVATE);

                    userId = sharedPreferences.getInt("userid",0);
                    username =sharedPreferences.getString("username","");
                    Chat tempChat = new Chat(userId, username,msg);
                    mSocket.send(tempChat.toString());
                    mChatArrayList.add(tempChat);
                    updateRecyclerView();//刷新RecyclerView
                    //清空输入栏
                    mInputText.setText("");
                }
            }
        });
    }


    class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        int mSpace;

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.left = 0;
            outRect.right = 0;
            outRect.bottom =0;
            if (parent.getChildAdapterPosition(view) != 0) {
                outRect.top = mSpace;
            }
            else{
                outRect.top=0;
            }

        }

        public SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }


    /**
     * 刷新view
     * */
    private void updateRecyclerView(){
        //当有新消息时，刷新RecyclerView中的显示
        mAdapter.notifyItemInserted(mChatArrayList.size() - 1);
        //将RecyclerView定位到最后一行
        mRecyclerView.scrollToPosition(mChatArrayList.size() - 1);
    }

    /**
     * 开启web socket连接
     * */
    private void start() {

        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(300, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(300, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(300, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        String token = "";
        sharedPreferences = getActivity().getSharedPreferences("mytoken", MODE_PRIVATE);

        token = sharedPreferences.getString("token", "");

        //定义request
        Request request = new Request.Builder().url("ws://10.23.34.211:3000/websocket/"+token).build();

        //绑定回调接口
        mOkHttpClient.newWebSocket(request, new FragmentOne.EchoWebSocketListener());
        mOkHttpClient.dispatcher().executorService().shutdown();

    }

    /**
     * 显示内容
     * */
    private void output(final Chat chat) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mChatArrayList.add(chat);
                updateRecyclerView();
            }
        });
    }

    /**
     * 初始化界面
     * */
    private void initView(){
        mInputText = getActivity().findViewById(R.id.input_text);
        mSend = getActivity().findViewById(R.id.send);
        mRecyclerView = getActivity().findViewById(R.id.msg_recycler_view);
    }

    /**
     * 静态方法返回一个能启动自己的intent
     * */
    public static Intent newIntent(Context context, String data){
        Intent intent = new Intent(context,FragmentOne.class);
        intent.putExtra("data",data);
        return intent;
    }

//    /**
//     * 对返回键的处理
//     * */
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event){
//        if(keyCode==KeyEvent.KEYCODE_BACK&&!backFlag){
//            Toast.makeText(FragmentOne.this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
//            backFlag = true;
//            return true;
//        }else {
//            return super.onKeyDown(keyCode, event);
//        }
//    }

    /**
     * 内部类，监听web socket回调
     * */
    private final class EchoWebSocketListener extends WebSocketListener {

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            mSocket = webSocket;    //实例化web socket
            Chat chat = new Chat();
            chat.setUserMsg(new Msg(false,"连接成功",true));
            output(chat);
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            super.onMessage(webSocket, text);
            Chat chat = JSON.parseObject(text, Chat.class);
            output(chat);
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            Chat chat = new Chat();
            chat.setUserMsg(new Msg(false,"关闭连接",true));
            output(chat);
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            Chat chat = new Chat();
            chat.setUserMsg(new Msg(false,"连接失败:"+t.getMessage(),true));
            output(chat);
        }
    }

}
